<?php

namespace Rjyst\RjLearnWord\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

class UninstallCommand extends Command
{
    protected $signature = 'rj-learn-word:uninstall {--force : Force uninstall without confirmation}';
    protected $description = 'Uninstall RjYst Learn Word package';

    public function handle()
    {
        $this->info('🗑️  开始卸载 RjYst Learn Word 扩展包...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要卸载 RjYst Learn Word 扩展包吗？这将删除所有相关文件和数据表！')) {
                $this->info('卸载已取消');
                return;
            }
        }

        // 1. 删除数据表
        $this->dropTables();

        // 2. 删除模型文件
        $this->deleteModels();

        // 3. 删除管理后台文件
        $this->deleteAdminFiles();

        // 4. 删除 Seeders
        $this->deleteSeeders();

        // 5. 删除迁移文件
        $this->deleteMigrations();

        // 6. 移除路由
        $this->removeRoute();

        // 7. 删除菜单
        $this->deleteMenu();

        // 8. 恢复 Category 模型
        $this->restoreCategoryModel();

        // 9. 恢复 ClickLearn 模型
        $this->restoreClickLearnModel();

        $this->info('🎉 RjYst Learn Word 扩展包卸载完成！');
    }

    protected function dropTables()
    {
        $this->info('删除数据表...');

        if (Schema::hasTable('learn_words')) {
            Schema::dropIfExists('learn_words');
            $this->info("✅ 删除表 learn_words");
        } else {
            $this->line("⚠️  表 learn_words 不存在");
        }
    }

    protected function deleteModels()
    {
        $this->info('删除模型文件...');

        $learnWordModel = app_path('Models/LearnWord/LearnWord.php');

        if (File::exists($learnWordModel)) {
            File::delete($learnWordModel);
            $this->info("✅ 删除模型: LearnWord.php");
        } else {
            $this->line("⚠️  模型不存在: LearnWord.php");
        }

        // 检查 LearnWord 目录是否为空，如果为空则删除
        $learnWordDir = app_path('Models/LearnWord');
        if (File::isDirectory($learnWordDir) && count(File::files($learnWordDir)) === 0) {
            File::deleteDirectory($learnWordDir);
            $this->info('✅ 删除空目录: Models/LearnWord');
        }
    }

    protected function deleteAdminFiles()
    {
        $this->info('删除管理后台文件...');

        $adminFiles = [
            app_path('Admin/Controllers/LearnWord/LearnWordController.php'),
            app_path('Admin/Repositories/LearnWord/ClickLearn.php'),
        ];

        foreach ($adminFiles as $filePath) {
            if (File::exists($filePath)) {
                File::delete($filePath);
                $this->info("✅ 删除文件: " . str_replace(app_path('Admin/'), '', $filePath));
            } else {
                $this->line("⚠️  文件不存在: " . str_replace(app_path('Admin/'), '', $filePath));
            }
        }

        // 检查并删除空目录
        $directories = [
            app_path('Admin/Controllers/LearnWord'),
            app_path('Admin/Repositories/LearnWord'),
        ];

        foreach ($directories as $dir) {
            if (File::isDirectory($dir) && count(File::allFiles($dir)) === 0) {
                File::deleteDirectory($dir);
                $this->info('✅ 删除空目录: ' . str_replace(app_path('Admin/'), 'Admin/', $dir));
            }
        }
    }

    protected function deleteSeeders()
    {
        $this->info('删除 Seeder 文件...');

        $seeders = [
            database_path('seeders/LearnWordDataSeeder.php'),
            database_path('seeders/LearnWordSeeder.php'),
        ];

        foreach ($seeders as $seederPath) {
            if (File::exists($seederPath)) {
                File::delete($seederPath);
                $this->info("✅ 删除 Seeder: " . basename($seederPath));
            } else {
                $this->line("⚠️  Seeder 不存在: " . basename($seederPath));
            }
        }
    }

    protected function deleteMigrations()
    {
        $this->info('删除迁移文件...');

        $migrationPath = database_path('migrations/2025_09_11_024206_create_learn_words_table.php');

        if (File::exists($migrationPath)) {
            File::delete($migrationPath);
            $this->info("✅ 删除迁移文件: 2025_09_11_024206_create_learn_words_table.php");
        } else {
            $this->line("⚠️  迁移文件不存在");
        }

        // 删除迁移记录
        try {
            DB::table('migrations')
                ->where('migration', '2025_09_11_024206_create_learn_words_table')
                ->delete();
            $this->info('✅ 删除迁移记录');
        } catch (\Exception $e) {
            $this->warn('⚠️  删除迁移记录失败: ' . $e->getMessage());
        }
    }

    protected function removeRoute()
    {
        $this->info('移除路由...');

        $routeFile = app_path('Admin/routes.php');

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  Admin routes.php 文件不存在');
            return;
        }

        $content = File::get($routeFile);

        // 查找并移除包含 learn_word 的路由行
        $lines = explode("\n", $content);
        $filteredLines = array_filter($lines, function($line) {
            return strpos($line, 'learn_word') === false;
        });

        if (count($filteredLines) < count($lines)) {
            $newContent = implode("\n", $filteredLines);
            // 清理多余的空行
            $newContent = preg_replace("/\n{3,}/", "\n\n", $newContent);

            File::put($routeFile, $newContent);
            $this->info('✅ 移除路由');
        } else {
            $this->line('⚠️  路由不存在');
        }
    }

    protected function deleteMenu()
    {
        $this->info('删除菜单...');

        try {
            $deleted = DB::table('admin_menu')
                ->where('uri', '/learn_word')
                ->delete();

            if ($deleted > 0) {
                $this->info('✅ 删除菜单');
            } else {
                $this->line('⚠️  菜单不存在');
            }

        } catch (\Exception $e) {
            $this->warn('⚠️  删除菜单失败: ' . $e->getMessage());
        }
    }

    protected function restoreCategoryModel()
    {
        $this->info('恢复 Category 模型...');

        $categoryModelPath = app_path('Models/Category/Category.php');

        if (!File::exists($categoryModelPath)) {
            $this->line('⚠️  Category 模型不存在');
            return;
        }

        $content = File::get($categoryModelPath);

        // 移除 LearnWord 相关的 use 语句
        $content = str_replace("use App\Models\LearnWord\LearnWord;\n", '', $content);
        $content = str_replace("\nuse App\Models\LearnWord\LearnWord;", '', $content);

        // 移除 learn_word 关联方法
        $learnWordMethodPattern = '/\s+public function learn_word\(\): Relations\\HasMany\s*\{[^}]*\}\s*/';
        $content = preg_replace($learnWordMethodPattern, '', $content);

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($categoryModelPath, $content);
        $this->info('✅ Category 模型恢复完成');
    }

    protected function restoreClickLearnModel()
    {
        $this->info('恢复 ClickLearn 模型...');

        $clickLearnModelPath = app_path('Models/Data/ClickLearn.php');

        if (!File::exists($clickLearnModelPath)) {
            $this->line('⚠️  ClickLearn 模型不存在');
            return;
        }

        $content = File::get($clickLearnModelPath);

        // 移除 LearnWord 相关的 use 语句
        $content = str_replace("use App\Models\LearnWord;\n", '', $content);
        $content = str_replace("\nuse App\Models\LearnWord;", '', $content);

        // 移除 learn_word 关联方法
        $learnWordMethodPattern = '/\s+public function learn_word\(\): Relations\\HasMany\s*\{[^}]*\}\s*/';
        $content = preg_replace($learnWordMethodPattern, '', $content);

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($clickLearnModelPath, $content);
        $this->info('✅ ClickLearn 模型恢复完成');
    }
}
